//
//  ProtocolsAndExtensions.swift
//  a_swift_tour
//
//  Created by yao_yu on 14-8-18.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import Foundation

func ProtocolsAndExtensions(){
    // P44
    var a = SimpleClass()
    a.adjust()
    let aDescription = a.simpleDescription
    //println(aDescription)
    
    var b = SimpleStructure()
    b.adjust()
    //println(b.simpleDescription)
    
    var c = SimpleEnum.One
    c.adjust()
    //println(c.simpleDescription)
    
    // P45
    var i = 7
    i.adjust()
    //println(i.simpleDescription)
    
    //结构是值拷贝, 修改protocolValue, 不影响i的值
    var protocolValue:ExampleProtocol = i
    protocolValue.adjust()
    //println(protocolValue.simpleDescription)
    
    //类是引用拷贝, 修改a, 等于修改protocolValue
    protocolValue = a
    a.adjust()
    //println(protocolValue.simpleDescription)
    
    // P46 练习
    var doubleValue = -1.0
    //println(doubleValue.absoluteValue)
}

// P43
protocol ExampleProtocol{
    var simpleDescription:String{get}
    mutating func adjust()
}

private class SimpleClass:ExampleProtocol{
    var simpleDescription:String = "A very simple class."
    var anotherProperty = 69105
    func adjust() {
        simpleDescription += " Now 100% adjusted."
    }
}

private struct SimpleStructure:ExampleProtocol{
    var simpleDescription:String = "A very simple structure."
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}

// P44页练习, iOS枚举中如何实现可写属性?
private enum SimpleEnum:ExampleProtocol{
    case One,Two
    var simpleDescription:String{
        switch self{
        case .One:
            return "A very simple enum(One)."
        case .Two:
            return "A very simple enum(Two)."
        }
    }
    mutating func adjust() {
        switch self{
        case .One:
            self = .Two
        case .Two:
            self = .One
        }
    }
}

// P45, 扩展
extension Int:ExampleProtocol{
    var simpleDescription:String{
        return "The number \(self)"
    }
    mutating func adjust(){
        self += 42
    }
}

// P46, 扩展练习
extension Double{
    var absoluteValue:Double{
        return self >= 0 ? self : -self
    }
}
